package service

import (
	"errors"
	"fmt"
	"math/rand"
	constant "rongyy/src/constants"
	"rongyy/src/middlewares"
	"rongyy/src/models"
	"strconv"
	"time"
)

type CaseService struct {
}

// CaseByCardNo
//
//	@Description: 查询出院记录，10天后可以申请
//	@receiver pc
//	@param req
//	@return *models.Resp4902
//	@return error
func (pc *CaseService) outRecord(req *models.Req4902Params) (*models.Resp4902, error) {
	data, err := (&HisService{}).GetAdmByCardNo(req)
	if data.ResultCode != "0" {
		return nil, errors.New(data.ResultMsg)
	}
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *CaseService) Create(req *models.CaseModel) (string, error) {
	rand.Seed(time.Now().UnixNano())
	t := rand.Intn(100)
	ts := strconv.FormatInt(time.Now().UnixMicro(), 10)
	sn := "c" + ts + strconv.Itoa(t)
	req.ApplySn = sn
	err := (&models.CaseModel{}).Create(req)
	if err != nil {
		middlewares.Logger.Println("CaseService Create failed ", err)
		return "", err
	}
	return sn, nil
}

func (pc *CaseService) Get(id int64) (*models.CaseModel, error) {
	data, err := (&models.CaseModel{}).GetById(id)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *CaseService) GetBySn(req *models.CaseModel) (*models.CaseModel, error) {
	data, has, err := (&models.CaseModel{}).FindBySn(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	if !has {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, fmt.Errorf("订单不存在")
	}
	return data, nil
}

func (pc *CaseService) Approve(req *models.CaseModel) error {
	req.Status = "approve"
	err := req.UpdateId()
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return err
	}
	cm, err := req.GetById(req.Id)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return err
	}
	fmt.Println("cm---------", cm.Id, cm)
	// 就医助手---病案通知
	go func() {
		reqMsg := &models.ReqNoticeParams{
			OpenId:        cm.Openid,
			PatName:       cm.PatientName,
			PatHospitalId: cm.PatientId,
			AuditStatus:   "审核通过",
			Id:            cm.Id,
		}
		middlewares.Logger.Println("发送消息入参", reqMsg)
		err = (&WxNoticeService{}).CaseNotice(reqMsg)
		if err != nil {
			middlewares.Logger.Println("发送消息错误", err)
		}
	}()
	return nil
}

func (pc *CaseService) Copy(id int64) error {
	cm := &models.CaseModel{}
	cm.Id = id
	c, err := cm.GetById(id)
	if err != nil {
		return err
	}
	if c.PayStatus != "paid" || c.Status != "confirm" {
		return fmt.Errorf("订单状态错误")
	}
	cm.Status = "copied"
	err = cm.UpdateId()
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return err
	}
	return nil
}

func (pc *CaseService) Reject(req *models.CaseModel) error {
	cm := &models.CaseModel{}
	c, err := cm.GetById(req.Id)
	if err != nil {
		return err
	}
	if c.Status != "pending" {
		return fmt.Errorf("订单状态错误")
	}
	req.Status = "reject"
	err = req.UpdateId()
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return err
	}
	return nil
}

func (pc *CaseService) Query(req *models.ReqCase) ([]models.CaseModel, int64, error) {
	data, total, err := (&models.CaseModel{}).Query(req)
	if err != nil {
		return nil, 0, err
	}
	return data, total, nil
}

func (pc *CaseService) Confirm(req *models.CaseModel) error {
	data, has, err := (&models.CaseModel{}).FindBySn(req)
	if !has {
		return fmt.Errorf("订单不存在")
	}
	if data.Status != "approve" && data.PayStatus != "paying" {
		return errors.New("订单状态错误")
	}
	req.Status = "confirm"
	req.PayStatus = "paid"
	err = req.ConfirmPay()
	if err != nil {
		return err
	}
	return nil
}
func (pc *CaseService) CompleteCopy(req *models.CaseModel) error {
	req.Status = "copied"
	req.CopyAt = time.Now().Format("2006-01-02 15:04:05")
	err := req.UpdateId()
	if err != nil {
		return err
	}
	return nil
}

func (pc *CaseService) PayCaseOne(req *models.CaseModel) (*models.CaseModel, error) {
	data, has, err := (&models.CaseModel{}).FindBySn(req)
	if !has {
		return nil, errors.New("订单不存在")
	}
	if data.Status != "approve" || data.PayStatus != "" {
		return nil, errors.New("订单状态错误")
	}
	return data, err
}

func (pc *CaseService) PayCase(req *models.CaseModel, ip string) (*models.PaymentRespData, string, error) {
	middlewares.Logger.Println("req==== ", req)
	rand.Seed(time.Now().UnixNano())
	t := rand.Intn(10000)
	ts := strconv.FormatInt(time.Now().UnixMicro(), 10)
	orderSn := "C" + ts + strconv.Itoa(t)
	fee, err := strconv.ParseFloat(req.Fee, 10)
	reqPay := &models.PaymentReq{
		MerchantId: constant.MerchantIdBAKD,
		Desc:       "病案快递费用",
		PayStatus:  "unpaid",
		OutTradeNo: orderSn,
		TotalFee:   fee,
		ClientIp:   ip,
		BusiType:   "case",
		OrderSn:    orderSn,
		PayWay:     constant.PayWay,
		OpenId:     req.Openid,
	}
	payResp, err := (&PaymentService{}).Pay(reqPay)
	middlewares.Logger.Println("payResp==== ", payResp)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, "", err
	}
	if payResp.ERRCODE != "000000" {
		return nil, "", errors.New(payResp.ERRMSG)
	}
	////请求支付成功,入库
	//cm := &models.CaseModel{
	//	OrderSn:   orderSn,
	//	PayStatus: "paying",
	//	ApplySn:   req.ApplySn,
	//	PatientId: req.PatientId,
	//	Openid:    req.Openid,
	//}
	//err = cm.UpdateApplySn()
	//if err != nil {
	//	middlewares.Logger.Println("病案快递支付中入库错误 failed ", err)
	//	return nil, "", err
	//}
	return payResp, orderSn, err
}

func (pc *CaseService) PayCaseThree(req *models.CaseModel, orderSn string) error {
	//请求支付成功,入库
	cm := &models.CaseModel{
		OrderSn:   orderSn,
		PayStatus: "paying",
		ApplySn:   req.ApplySn,
		PatientId: req.PatientId,
		Openid:    req.Openid,
	}
	err := cm.UpdateApplySn()
	if err != nil {
		middlewares.Logger.Println("病案快递支付中入库错误 failed ", err)
		return err
	}
	return err
}

func (pc *CaseService) Cancel(req *models.CaseModel) error {
	data, has, err := (&models.CaseModel{}).FindBySn(req)
	if !has {
		return fmt.Errorf("订单不存在")
	}
	if !(data.Status == "approve" || data.Status == "pending") {
		return errors.New("订单状态错误")
	}
	req.Status = "cancel"
	req.Remark = "患者自主取消"
	err = req.UpdateApplySn()
	if err != nil {
		return err
	}
	return nil
}

func (pc *CaseService) Refund(req *models.CaseModel) error {
	data, has, err := (&models.CaseModel{}).FindBySn(req)
	if !has {
		return fmt.Errorf("订单不存在")
	}
	if data.Status != "confirm" && data.PayStatus != "paid" {
		return errors.New("订单状态错误")
	}

	req.Status = "refunding"
	req.Remark = "患者自主取消并退费"
	err = req.UpdateApplySn()
	if err != nil {
		return err
	}

	// 退款缺失
	fee, _ := strconv.ParseFloat(data.Fee, 64)
	refundReq := &models.RefundReq{
		Id:         constant.MerchantId,
		ReturnCode: "refund_sn",
		OrderSn:    data.OrderSn,
		RefundFee:  fee,
		BusiType:   "case",
	}
	resp, err := (&PaymentService{}).Refund(refundReq)
	if !resp.IsSuccess {
		return errors.New(resp.Msg)
	}
	if resp.Data.ReturnCode != "000000" {
		return errors.New(resp.Data.ReturnMsg)
	}

	hrm := &models.RefundModel{
		OrderSn:   data.OrderSn,
		RefundSn:  resp.Data.CustId,
		RefundFee: resp.Data.TxInfo.Amount,
		Remark:    "病案快递-患者自助退费",
	}
	err = hrm.Create()
	if err != nil {
		middlewares.Logger.Println("reg HisRefundModel create failed", data.OrderSn, err)
	}
	req.Status = "refunded"
	data.RefundSn = resp.Data.CustId
	req.Remark = "患者自主取消并退费"
	err = req.UpdateApplySn()
	if err != nil {
		middlewares.Logger.Println("reg UpdateRefund failed", data.OrderSn, err)
		return err
	}
	return nil
}

func (pc *CaseService) DeliveryAddSn(req *models.CaseModel) error {
	data, has, err := (&models.CaseModel{}).FindBySn(req)
	if !has {
		return fmt.Errorf("订单不存在")
	}
	if !(data.Status == "copied" || data.Status == "paid") {
		return errors.New("订单状态错误")
	}
	req.Status = "complete"
	err = req.UpdateApplySn()
	if err != nil {
		return err
	}
	return nil
}
